<?php

namespace app\index\controller;

use app\index\model\Comment;
use app\index\model\CtmStaff;
use app\index\model\Miaosha;
use app\index\model\Order;
use app\index\model\Qianggou;
use app\index\model\RedpacketCustom;
use app\index\model\Servicenews;
use app\index\model\StaffStatistic;
use app\index\model\Store;
use think\Controller;
use think\Db;
use app\index\model\CtmVip;
use app\index\model\Ctmmoneyflow;
use app\util\Utils;
use app\index\model\Custom;
use app\util\Alipay;
use app\util\WxPay;
use think\Log;
use app\index\model\CtmCun;

/*
 * 订单更新状态
 */

class OrderController extends Controller {
    /*
     * 定时更新订单状态
     *
     * 订单状态为服务中(7)和美容师服务完成(8)时，如果客户没有确认服务完成，自动更新为服务完成(9)
     */

    public function updateOrderStatus() {
        Db::name('aaa')->insert([
            'order_id' => time(),
        ]);

        $now = time();

        $ctmStaffList = CtmStaff::with('order,item')
                ->where('status', 'in', [Order::STATUS_7, Order::STATUS_8])
                ->field('id, staff_id, item_id, order_id, status, started_time')
                ->order('add_time desc')
                ->select();

        if (count($ctmStaffList) > 0) {
            foreach ($ctmStaffList as $key => $value) {
                $yuyue_id = $value['id'];
                $staff_id = $value['staff_id'];
                $order_id = $value['order_id'];
                $started_time = $value['started_time'];
                $orderStatus = $value['order']['status'];
                $service_time = $value['item']['service_time'];
                if (is_numeric($service_time)) {
                    $service_time = $service_time * 60;
                } else {
                    $service_time = 1800;
                }

                if (intval($started_time) != 0) {
                    $yuyueStatus = Order::STATUS_9;
                    $orderStatus = Order::getOrderStatus($order_id, $yuyue_id, $orderStatus, $yuyueStatus);
                    $ended_time = $started_time + $service_time + 1200;

                    if ($now > $ended_time) {
                        Db::startTrans();

                        $orderResult = Order::where('id', '=', $order_id)->update([
                            'status' => $orderStatus,
                            'update_time' => $now,
                        ]);

                        $ctmStaffData = [
                            'status' => $yuyueStatus,
                        ];
                        if ($value['status'] == Order::STATUS_7) {
                            $ctmStaffData['end_time'] = $ended_time;
                            $ctmStaffData['ended_time'] = $ended_time;
                        } else if ($value['status'] == Order::STATUS_8) {
                            $ctmStaffData['ended_time'] = $ended_time;
                        }
                        $ctmStaffResult = CtmStaff::where('id', '=', $yuyue_id)->update($ctmStaffData);

                        $income = CtmStaff::getCtmStaffIncome($yuyue_id);
                        if ($income > 0) {
                            $day_time = date('Y-m-d', $now);

                            $row = StaffStatistic::where('staff_id', '=', $staff_id)
                                ->where('day_time', '=', $day_time)
                                ->find();
                            if (is_null($row)) {
                                $statisticData = [
                                    'staff_id' => $staff_id,
                                    'money' => $income,
                                    'day_time' => $day_time
                                ];

                                $statisticResult = StaffStatistic::insert($statisticData);
                            } else {
                                $statisticData = [
                                    'money' => bcadd($row['money'], $income, 2),
                                ];

                                $statisticResult = StaffStatistic::where('id', '=', $row['id'])
                                    ->update($statisticData);
                            }
                        } else {
                            $statisticResult = true;
                        }

                        if ($orderResult && $ctmStaffResult && $statisticResult) {
                            Db::commit();
                            echo '<script>window.close();</script>';
                        } else {
                            Db::rollback();
                        }
                    }
                }
            }
        }
    }

    /*
     * 定时更新订单状态
     *
     * 定时退回 余额不足时生成的订单
     * 订单状态为1且vip_money不为0的订单 更新状态为0
     * 更新用户余额
     * 写入流水
     */

    public function saveOrderStatus() {
        $now = time();

        $orderlist = Db::name('order')->alias('o')
                ->join('ord_pro op', 'op.ord_id = o.id')
                ->where('o.status', '=', Order::STATUS_1)
                //->where('o.vip_money', '>', 0)
                ->where('op.type', 'in', [Order::TYPE_5, Order::TYPE_6])
                ->where('o.add_time', '<', $now - 300)
                ->field('o.id,o.store_id,o.ctm_id,o.vip_id,o.vip_money,o.red_money,op.pro_id,op.type,op.number,o.ord_num')
                ->select();
        //print_r($orderlist);
        if (count($orderlist) > 0) {
            foreach ($orderlist as $key => $value) {
                $id = $value['id'];
                $store_id = $value['store_id'];
                $ctm_id = $value['ctm_id'];
                $vip_id = $value['vip_id'];
                $vip_money = $value['vip_money'];
                $red_money = $value['red_money'];
                $pro_id = $value['pro_id'];
                $type = $value['type'];
                $number = $value['number'];
                $ord_num = $value['ord_num'];

                $wxpay = new WxPay();
                $array_data = $wxpay->AppWxAudit($ord_num);
                if ($array_data['return_code'] == 'SUCCESS' && $array_data['result_code'] == 'SUCCESS' && $array_data['trade_state'] == 'SUCCESS') {
                    continue;
                }
                $array_data = $wxpay->H5WxAudit($ord_num);
                if ($array_data['return_code'] == 'SUCCESS' && $array_data['result_code'] == 'SUCCESS' && $array_data['trade_state'] == 'SUCCESS') {
                    continue;
                }

                $alipay = new Alipay();
                $alipayResult = $alipay->doQuery($ord_num);
                if ($alipayResult->code == 10000 && ($alipayResult->trade_status == 'TRADE_SUCCESS' || $alipayResult->trade_status == 'TRADE_FINISHED')) {
                    continue;
                }

                Db::startTrans();

                if ($vip_money > 0) {
                    $ctmvipdata = CtmVip::where('ctm_id', '=', $ctm_id)
                        ->where('vipcard_id', '=', $vip_id)
                        ->find();
                    $residue = $ctmvipdata['residue'] + $vip_money;
                    $savectmvip = CtmVip::where('ctm_id', '=', $ctm_id)
                        ->where('vipcard_id', '=', $vip_id)
                        ->update(['residue' => $residue]);

                    $telephone = Custom::where('id', '=', $ctm_id)->value('custom_phone');
                    $flow_number = Utils::generateFlowNumber($telephone);
                    $savectmmoneyflow = Ctmmoneyflow::insert([
                        'type' => Ctmmoneyflow::TYPE_1,
                        'item_type' => $type,
                        'pay_method' => Ctmmoneyflow::PAY_METHOD_2,
                        'store_id' => $store_id,
                        'ctm_id' => $ctm_id,
                        'item_id' => $pro_id,
                        'money' => $vip_money,
                        'last_money' => $residue,
                        'flow_number' => $flow_number,
                        'vipid' => $vip_id,
                        'add_time' => time(),
                    ]);

                } else {
                    $savectmvip = true;
                    $savectmmoneyflow = true;
                }

                if ($type == Order::TYPE_5) {
                    $miaoshaRow = Miaosha::where('id', '=', $pro_id)
                        ->field('number, sell_count')
                        ->find();

                    $miaoshaResult = Miaosha::where('id', '=', $pro_id)->update([
                        'number' => $miaoshaRow['number'] + $number,
                        'sell_count' => $miaoshaRow['sell_count'] - $number,
                    ]);
                } else if ($type == Order::TYPE_6) {
                    $qianggouRow = Qianggou::where('id', '=', $pro_id)
                        ->field('sell_count')
                        ->find();

                    $miaoshaResult = Qianggou::where('id', '=', $pro_id)->update([
                        'sell_count' => $qianggouRow['sell_count'] - $number,
                    ]);
                } else {
                    $miaoshaResult = true;
                }

                if ($red_money > 0) {
                    $last_red_money = Custom::where('id', '=', $ctm_id)->value('red_money');
                    $last_red_money = bcadd($last_red_money, $red_money, 2);
                    $customResult = Custom::where('id', '=', $ctm_id)->update(['red_money' => $last_red_money]);

                    $redCtmData = [
                        'store_id' => $store_id,
                        'custom_id' => $ctm_id,
                        'redpacket_id' => 0,
                        'money' => $red_money,
                        'status' => RedpacketCustom::STATUS_2,
                        'add_time' => $now,
                    ];
                    $redCtmResult = RedpacketCustom::insert($redCtmData);
                } else {
                    $customResult = true;
                    $redCtmResult = true;
                }

                $saveorder = Order::where('id', '=', $id)->update([
                    'status' => Order::STATUS_0,
                    'cancel_time' => time(),
                    'update_time' => time(),
                ]);

                if ($savectmvip && $savectmmoneyflow && $miaoshaResult && $customResult && $redCtmResult && $saveorder) {
                    Db::commit();
                } else {
                    Db::rollback();
                }
            }
        }
    }

    /*
     * 定时更新订单状态（72小时未支付取消订单）
     *
     * 定时退回 余额不足时生成的订单
     * 订单状态为1且vip_money不为0的订单 更新状态为0
     * 更新用户余额
     * 写入流水
     */

    public function cancelOrderStatus() {
        $now = time();

        $orderlist = Db::name('order')->alias('o')
            ->join('ord_pro op', 'op.ord_id = o.id')
            ->where('o.status', '=', Order::STATUS_1)
            ->where('op.type', 'not in', [Order::TYPE_5, Order::TYPE_6])
            ->where('o.add_time', '<', $now - 259200)
            ->field('o.id,o.store_id,o.ctm_id,o.vip_id,o.vip_money,o.red_money,op.pro_id,op.type,op.number,o.ord_num,o.cun_id')
			->order('add_time desc')
			->limit(0, 10)
            ->select();
        //print_r($orderlist);
        if (count($orderlist) > 0) {
            foreach ($orderlist as $key => $value) {
                $id = $value['id'];
                $store_id = $value['store_id'];
                $ctm_id = $value['ctm_id'];
                $vip_id = $value['vip_id'];
                $vip_money = $value['vip_money'];
                $red_money = $value['red_money'];
                $pro_id = $value['pro_id'];
                $type = $value['type'];
                $number = $value['number'];
                $ord_num = $value['ord_num'];
                $cun_id = $value['cun_id'];
                //判断是否使用了代金券
                if ($cun_id != 0) {
                    $ctmCunResult = CtmCun::where('id', '=', $cun_id)->update(['employ' => CtmCun::EMPLOY_2]);
                } else {
                    $ctmCunResult = true;
                }

                $wxpay = new WxPay();
                $array_data = $wxpay->AppWxAudit($ord_num);
                if ($array_data['return_code'] == 'SUCCESS' && $array_data['result_code'] == 'SUCCESS' && $array_data['trade_state'] == 'SUCCESS') {
                    continue;
                }
                $array_data = $wxpay->H5WxAudit($ord_num);
                if ($array_data['return_code'] == 'SUCCESS' && $array_data['result_code'] == 'SUCCESS' && $array_data['trade_state'] == 'SUCCESS') {
                    continue;
                }

                $alipay = new Alipay();
                $alipayResult = $alipay->doQuery($ord_num);
                if ($alipayResult->code == 10000 && ($alipayResult->trade_status == 'TRADE_SUCCESS' || $alipayResult->trade_status == 'TRADE_FINISHED')) {
                    continue;
                }

                Db::startTrans();

                if ($vip_money > 0) {
                    $ctmvipdata = CtmVip::where('ctm_id', '=', $ctm_id)
                        ->where('vipcard_id', '=', $vip_id)
                        ->find();
                    $residue = $ctmvipdata['residue'] + $vip_money;
                    $savectmvip = CtmVip::where('ctm_id', '=', $ctm_id)
                        ->where('vipcard_id', '=', $vip_id)
                        ->update(['residue' => $residue]);

                    $telephone = Custom::where('id', '=', $ctm_id)->value('custom_phone');
                    $flow_number = Utils::generateFlowNumber($telephone);
                    $savectmmoneyflow = Ctmmoneyflow::insert([
                        'type' => Ctmmoneyflow::TYPE_1,
                        'item_type' => $type,
                        'pay_method' => Ctmmoneyflow::PAY_METHOD_2,
                        'store_id' => $store_id,
                        'ctm_id' => $ctm_id,
                        'item_id' => $pro_id,
                        'money' => $vip_money,
                        'last_money' => $residue,
                        'flow_number' => $flow_number,
                        'vipid' => $vip_id,
                        'add_time' => time(),
                    ]);

                } else {
                    $savectmvip = true;
                    $savectmmoneyflow = true;
                }

                if ($red_money > 0) {
                    $last_red_money = Custom::where('id', '=', $ctm_id)->value('red_money');
                    $last_red_money = bcadd($last_red_money, $red_money, 2);
                    $customResult = Custom::where('id', '=', $ctm_id)->update(['red_money' => $last_red_money]);

                    $redCtmData = [
                        'store_id' => $store_id,
                        'custom_id' => $ctm_id,
                        'redpacket_id' => 0,
                        'money' => $red_money,
                        'status' => RedpacketCustom::STATUS_2,
                        'add_time' => $now,
                    ];
                    $redCtmResult = RedpacketCustom::insert($redCtmData);
                } else {
                    $customResult = true;
                    $redCtmResult = true;
                }

                $saveorder = Order::where('id', '=', $id)->update([
                    'status' => Order::STATUS_0,
                    'cancel_time' => time(),
                    'update_time' => time(),
                ]);

                if ($savectmvip && $savectmmoneyflow && $customResult && $redCtmResult && $saveorder && $ctmCunResult) {
                    Db::commit();
                } else {
                    Db::rollback();
                }
            }
        }
    }

    /*
     * 预约自动评价
     * 30天没有评价自动好评
     */
    public function autoComment()
    {
        $now = time();

        $start_time = strtotime('2018-04-15');

        $ended_time = $now - 2592000;

        $row = CtmStaff::with('item,order.ordPro')
            ->where('status', '=', Order::STATUS_9)
            ->where('ended_time', '>=', $start_time)
            ->where('ended_time', '<', $ended_time)
            ->field('id, staff_id, ctm_id, item_id, store_id, order_id')
            ->order('id desc')
            ->find();

        if (!is_null($row)) {
            Db::startTrans();

            $order_id = $row['order_id'];
            $yuyue_id = $row['id'];
            $staff_id = $row['staff_id'];
            $store_id = $row['store_id'];
            $ctm_id = $row['ctm_id'];
            $item_id = $row['item_id'];
            $item_name = $row['item']['item_name'];
            $price = $row['order']['ord_pro']['price'];
            $status = $row['order']['status'];

            $commentData = [
                'type' => Comment::TYPE_1,
                'order_id' => $order_id,
                'yuyue_id' => $yuyue_id,
                'staff_id' => $staff_id,
                'store_id' => $store_id,
                'ctm_id' => $ctm_id,
                'item_id' => $item_id,
                'item_name' => $item_name,
                'price' => $price,
                'content' => '系统默认好评',
                'image' => null,
                'star' => 5,
                'staff_star' => 5,
                'add_time' => $now,
            ];
            $insertId = Comment::insertGetId($commentData);

            $yuyueStatus = Order::STATUS_10;
            $orderStatus = Order::getOrderStatus($order_id, $yuyue_id, $status, $yuyueStatus);

            $orderResult = Order::where('id', '=', $order_id)->update([
                'status' => $orderStatus,
                'update_time' => $now,
            ]);
            $ctmStaffResult = CtmStaff::where('id', '=', $yuyue_id)->update(['status' => $yuyueStatus, 'comment_time' => $now]);

            if ($insertId && $orderResult && $ctmStaffResult) {
                Db::commit();

                //预约信息
                $ctmStaffRow = CtmStaff::with('custom,staff,item')
                    ->where('id', '=', $yuyue_id)
                    ->field('id, staff_id, ctm_id, item_id, store_id')
                    ->find();
                $custom_name = strlen($ctmStaffRow['custom']['custom_name']) > 0 ? $ctmStaffRow['custom']['custom_name'] : $ctmStaffRow['custom']['custom_phone'];

                //给店铺发推送
                $staffRow = Store::getStoreStaff($store_id);
                $content = "【收到评价】[{$custom_name}] 刚刚评论了 [{$ctmStaffRow['staff']['staff_name']}] 的 [{$ctmStaffRow['item']['item_name']}] 服务";
                $msgContent = Utils::getColoredString($content);
                $pushContent = Utils::getPushString($content);
                $alias = $staffRow['staff']['telephone'] . $store_id;
                $userid = $staffRow['staff']['id'];
                Utils::sendServicenews(Servicenews::TITLEID_11, $insertId, 0, $msgContent, $userid, Servicenews::TYPE_1, $ctmStaffRow['store_id'], [
                    'title' => '评价消息',
                    'content' => $pushContent,
                    'alias_type' => Servicenews::ALIAS_TYPE_1,
                    'alias' => $alias,
                ]);

                //给美容师发推送
                $content = "【收到评价】[{$custom_name}] 刚刚评论了您的服务";
                $msgContent = Utils::getColoredString($content);
                $pushContent = Utils::getPushString($content);
                $alias = $ctmStaffRow['staff']['telephone'] . $store_id;
                $userid = $ctmStaffRow['staff']['id'];
                Utils::sendServicenews(Servicenews::TITLEID_11, $insertId, 0, $msgContent, $userid, Servicenews::TYPE_1, $ctmStaffRow['store_id'], [
                    'title' => '评价消息',
                    'content' => $pushContent,
                    'alias_type' => Servicenews::ALIAS_TYPE_1,
                    'alias' => $alias,
                ]);
            } else {
                Db::rollback();
            }

        }
    }

    public function aaa()
    {
        Log::info(6000000);
        Log::info(time() . '----------');
    }




}
